import React, { useEffect, useRef, useState } from 'react';

interface VideoTextProps {
  splitTexts?: string[]; // 分段文本数组
  highlightTexts?: string[]; // 高亮文本数组，替换原来的单个 highlightText
  fontSize?: number;
  style?: React.CSSProperties;
  fontFamily?: string; // 新增字体配置
}

const VideoText: React.FC<VideoTextProps> = ({
  splitTexts = [], // 提供默认空数组
  highlightTexts = [], // 提供默认空数组
  fontSize = 60,
  style = {},
  fontFamily = 'YouSheBiaoTiHei', // 提供默认字体
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const startTimeRef = useRef<number | null>(null);
  const [windowSize, setWindowSize] = useState({
    width: Math.min(800, window.innerWidth), // 限制最大宽度
    height: 300, // 固定高度
  });
  const HIGHLIGHT_DELAY = 500; // 高亮文字延迟0.5秒后开始
  const CHAR_DURATION = 1000; // 每个字符的动画持续时间
  const [fontLoaded, setFontLoaded] = useState(false);

  const normalColors = {
    fill: '#FFFFFF', // 普通文字填充色（纯白色）
    stroke: '#4B7BE5', // 普通文字描边色（亮蓝色）
  };

  const highlightColors = {
    fill: '#FDD835', // 高亮文字填充色（明亮的黄色）
    stroke: '#4B7BE5', // 高亮文字描边色（亮蓝色）
  };

  // 计算每行能容纳的最大宽度（考虑padding）
  const maxLineWidth = windowSize.width - 40; // 左右各留20px的padding

  // 修改字体设置部分
  const getFont = (isBold = false) => {
    const weight = isBold ? 'bold' : 'normal';
    return `${weight} ${fontSize}px "${fontFamily}", Arial`; // 使用传入的字体
  };

  // 初始化 canvas
  const initCanvas = () => {
    const canvas = canvasRef.current as HTMLCanvasElement;
    if (!canvas) return null;
    const ctx = canvas.getContext('2d');

    // 设置实际渲染尺寸（考虑设备像素比）
    const dpr = window.devicePixelRatio || 1;
    canvas.width = windowSize.width * dpr;
    canvas.height = windowSize.height * dpr;

    // 设置显示尺寸
    canvas.style.width = `${windowSize.width}px`;
    canvas.style.height = `${windowSize.height}px`;

    // 缩放上下文以匹配设备像素比
    ctx?.scale(dpr, dpr);

    return ctx;
  };

  // 修改动画函数的类型定义
  const animate = useRef<
    (ctx: CanvasRenderingContext2D | null) => (() => void) | undefined
  >(() => undefined); // 提供初始值
  const animationFrameId = useRef<number | undefined>(undefined);

  // 添加一个 resize 处理函数
  const handleResize = () => {
    setWindowSize({
      width: Math.min(800, window.innerWidth),
      height: 200,
    });
  };

  // 监听窗口大小变化
  useEffect(() => {
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 添加字体加载检查
  useEffect(() => {
    const font = new FontFace('YouSheBiaoTiHei', 'Arial');

    font
      .load()
      .then(() => {
        document.fonts.add(font);
        setFontLoaded(true);
      })
      .catch((err) => {
        console.error('Font loading failed:', err);
        setFontLoaded(false);
      });
  }, []);

  // 添加缺失的动画辅助函数
  const easeOutCubic = (t: number): number => {
    return 1 - Math.pow(1 - t, 3);
  };

  const getHighlightProgress = (
    charIndex: number,
    currentTime: number,
  ): number => {
    const timeSinceStart = currentTime - (startTimeRef.current || 0);
    const delay = HIGHLIGHT_DELAY + charIndex * 100; // 每个字符延迟100ms
    const duration = CHAR_DURATION;

    if (timeSinceStart < delay) return 0;
    if (timeSinceStart > delay + duration) return 1;

    return (timeSinceStart - delay) / duration;
  };

  const getSlideInOffset = (charIndex: number, progress: number): number => {
    if (progress >= 1) return 0;
    const offset = 50 * (1 - easeOutCubic(progress));
    return offset;
  };

  // 修改初始化动画函数
  useEffect(() => {
    animate.current = (ctx: CanvasRenderingContext2D | null) => {
      if (!ctx || !splitTexts.length) return;

      const x = windowSize.width / 2;
      let angle = 0;
      const animationStartTime = Date.now();

      const drawText = () => {
        if (!ctx) return;

        const currentTime = Date.now();
        const elapsed = currentTime - animationStartTime;

        // 计算进度，但不再循环
        const progress = Math.min(elapsed / 2000, 1);

        ctx.clearRect(0, 0, windowSize.width, windowSize.height);

        // 只在动画进行时更新角度
        if (progress < 1) {
          angle += 0.02;
        }

        // 应用阴影效果
        ctx.shadowOffsetX = Math.sin(angle) * 2;
        ctx.shadowOffsetY = Math.cos(angle) * 2;
        ctx.shadowBlur = 4;
        ctx.shadowColor = normalColors.stroke;

        // 普通文字的动画进度 (0-0.6)
        const normalProgress = Math.min(progress / 0.6, 1);

        // 高亮文字的动画进度 (0.3-1.0)
        const highlightProgress = Math.max(
          0,
          Math.min((progress - 0.3) / 0.7, 1),
        );

        // 设置基础字体
        ctx.font = getFont();
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.lineWidth = 2;

        // 计算文字布局
        const lineHeight = fontSize * 1.5;
        const totalHeight = splitTexts.length * lineHeight;
        const startY = (windowSize.height - totalHeight) / 2 + lineHeight / 2;

        // 逐行绘制文字
        splitTexts.forEach((line, lineIndex) => {
          if (!line) return;

          const chars = line.split('');
          const charWidth = ctx.measureText('家').width;
          const lineWidth = charWidth * chars.length;
          const startX = x - lineWidth / 2 + charWidth / 2;
          const y = startY + lineIndex * lineHeight;

          // 确保行宽不超过最大宽度
          if (lineWidth <= maxLineWidth) {
            // 先绘制普通文字
            chars.forEach((char, index) => {
              const isHighlight = highlightTexts.some((highlight) => {
                const highlightStart = line.indexOf(highlight);
                return (
                  highlightStart !== -1 &&
                  index >= highlightStart &&
                  index < highlightStart + highlight.length
                );
              });

              if (!isHighlight) {
                const charProgress = Math.max(
                  0,
                  Math.min(1, normalProgress * 2 - index * 0.1),
                );
                if (charProgress > 0) {
                  ctx.save();
                  const xPos = startX + index * charWidth;
                  const yOffset = Math.sin(angle + index * 0.5) * 2;

                  ctx.translate(xPos, y + yOffset);
                  ctx.strokeStyle = normalColors.stroke;
                  ctx.fillStyle = normalColors.fill;
                  ctx.globalAlpha = charProgress;

                  ctx.strokeText(char, 0, 0);
                  ctx.fillText(char, 0, 0);
                  ctx.restore();
                }
              }
            });

            // 然后绘制高亮文字，但要等普通文字动画完成后
            if (highlightProgress > 0) {
              highlightTexts.forEach((highlight) => {
                const highlightStart = line.indexOf(highlight);
                if (highlightStart !== -1) {
                  const highlightChars = highlight.split('');
                  highlightChars.forEach((char, idx) => {
                    const index = highlightStart + idx;
                    const charHighlightProgress = Math.max(
                      0,
                      Math.min(1, highlightProgress * 2 - idx * 0.1),
                    );

                    if (charHighlightProgress > 0) {
                      ctx.save();
                      const xPos = startX + index * charWidth;
                      const yOffset = Math.sin(angle + index * 0.5) * 2;

                      ctx.translate(xPos, y + yOffset);
                      ctx.font = getFont(true);
                      ctx.strokeStyle = highlightColors.stroke;
                      ctx.fillStyle = highlightColors.fill;
                      ctx.globalAlpha = charHighlightProgress;

                      // 添加缩放效果
                      const scale =
                        1 + Math.sin(charHighlightProgress * Math.PI) * 0.2;
                      ctx.scale(scale, scale);

                      ctx.strokeText(char, 0, 0);
                      ctx.fillText(char, 0, 0);
                      ctx.restore();
                    }
                  });
                }
              });
            }
          }
        });

        // 只在动画未完成时继续请求动画帧
        if (progress < 1) {
          animationFrameId.current = requestAnimationFrame(drawText);
        }
      };

      drawText();

      return () => {
        if (animationFrameId.current) {
          cancelAnimationFrame(animationFrameId.current);
        }
      };
    };
  }, [splitTexts, highlightTexts, fontSize, windowSize, fontFamily]);

  // 添加一个新的 effect 来处理动画的重启
  useEffect(() => {
    const ctx = initCanvas();
    if (ctx) {
      const cleanup = animate.current(ctx);
      return () => {
        if (cleanup) cleanup();
      };
    }
  }, []);

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        padding: '20px 0',
        position: 'relative',
        zIndex: 1,
        color: '#FFFFFF',
        fontFamily: fontLoaded ? 'YouSheBiaoTiHei' : 'Arial',
        fontSize: `${fontSize}px`,
        textShadow: '2px 2px 4px #4B7BE5',
        WebkitTextStroke: '1px #4B7BE5',
        ...style,
      }}
    >
      <style>
        {`
          @font-face {
            font-family: 'YouSheBiaoTiHei';
          }
        `}
      </style>
      <canvas
        ref={canvasRef}
        style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          background: 'transparent',
          color: '#FFFFFF',
          fontFamily: fontLoaded ? 'YouSheBiaoTiHei' : 'Arial',
          fontSize: `${fontSize}px`,
          textShadow: '1px 1px 3px #4B7BE5',
          WebkitTextStroke: '1px #4B7BE5',
          zIndex: 10,
          pointerEvents: 'none',
        }}
      />
    </div>
  );
};

export default VideoText;
